package yxy.game.pm2.command.soloride;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Hero;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.SoloRideMessage;
import yxy.game.pm2.module.hero.HeroHandle;
import yxy.game.pm2.module.soloride.SoloRideModule;

import java.util.Collection;

/** 千里走单骑 千里走单骑选武将界面 */
@MessageType(proto = Command.SoloRideSelectHero, classtype = SoloRideMessage.SoloRideSelectHeroRequest.class)
public class CMD_SoloRideSelectHero extends Command<SoloRideMessage.SoloRideSelectHeroRequest> {

	@Override
	public void execute(MessageSource messageSource, SoloRideMessage.SoloRideSelectHeroRequest request) {
		String playerCode = messageSource.getTag();

		SoloRideMessage.SoloRideSelectHeroResponse.Builder response = SoloRideMessage.SoloRideSelectHeroResponse.newBuilder();

		SoloRideModule soloRideModule = SoloRideModule.get(playerCode);
		if (soloRideModule == null) {
			send(messageSource, response, Result.ModuleNotOpen);// 模块没开启
			return;
		}

		try {
			if (soloRideModule.tryLock()) {
				if (soloRideModule.isBattling()) {
					send(messageSource, response, Result.BattleIsRunning);// 之前的战斗未结束
					return;
				}
				HeroHandle heroHandle = new HeroHandle();
				Collection<Hero> heros = heroHandle.getHeros(playerCode);
				for (Hero hero : heros) {
					try {
						response.addHeros(heroHandle.getHeroSimple(playerCode, hero));
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				if (soloRideModule.getHero() != null) {
					response.setHero(soloRideModule.getHero().getCode());
				}
				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			soloRideModule.unlock();
		}
	}

	private void send(MessageSource messageSource, SoloRideMessage.SoloRideSelectHeroResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}